import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select, Tooltip,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';

import find from 'lodash/find';
import debounce from 'lodash/debounce';
import {ellipsis, afterCloseModal, DescriptionItem, download, formateObjToParamStr} from '@/utils/utils';
import { routerRedux } from 'dva/router';
import BuildModalTitle from '@/components/BuildModalTitle';
import ReactDataGrid from 'react-data-grid';
import AddOrEditUser from './addOrEditUser';
import Detail from './Detail';
import Evaluate from './evaluate';
import request from '@/utils/request';
import config from "@/config/config";

const FormItem = Form.Item;
const { confirm } = Modal;
const { Option } = Select;

const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ work_orders_list, loading, global }) => ({
  work_orders_list,
  global,
  loading: loading.models.work_orders_list,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      users:[]
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      work_orders_list: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        work_orders_list: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'work_orders_list/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'work_orders_list/changeLoaded',
          });
          dispatch({
            type: 'work_orders_list/changeTableY',
          });
        },
      });

    }
    const that = this;
    request(`/search_users`, {
      method: 'GET',
      params:{
        inspector:1,
        per_page:100
      }
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          users: response.data.data,
        });
      }

    });
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'work_orders_list/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'work_orders_list/changeTableY',
    });
  };
  findChildFunc = (cb) => {
    this.file = cb;
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    const table = document.querySelector('.react-grid-Canvas');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'work_orders_list/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      work_orders_list: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem label={'开始时间'}>
          {getFieldDecorator('start_time', {
            initialValue: moment(searchParams.start_time),
          })(
            <DatePicker
              style={{width:'120px'}}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />
          )}
        </FormItem>
        <FormItem label={'结束时间'}>
          {getFieldDecorator('end_time', {
            initialValue: moment(searchParams.end_time),
          })(
            <DatePicker
              style={{width:'120px'}}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />
          )}
        </FormItem>
        <FormItem>
          <FormItem label="优先级">
            {getFieldDecorator('priority', {
              initialValue: searchParams.priority,
            })(
              <Select  style={{width:'100px'}}>
                <Option value={''}>全部</Option>
                <Option value={'一般'}>一般</Option>
                <Option value={'紧急'}>紧急</Option>
              </Select>
            )}
          </FormItem>
          <FormItem label="状态">
            {getFieldDecorator('status', {
              initialValue: searchParams.status,
            })(
              <Select style={{width:'150px'}}>
                {
                  [{id:'',value:'全部'},{id:'-1',value:'已取消'},{id:'1',value:'未派工'}
                    ,{id:'2',value:'已派工、处理中'},{id:'3',value:'已完成、未评价'},{id:'4',value:'已完成、已评价'}].map((item,index)=>{
                    return <Option key={index} value={item.id}>{item.value}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                  start_time:  moment(fieldsValue.start_time).format('YYYY-MM-DD'),
                  end_time:  moment(fieldsValue.end_time).format('YYYY-MM-DD'),
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
          {
            <Button
              icon="plus"
              style={{ marginLeft: 8 }}
              type="primary"
              onClick={
                () => {
                  if(!sessionStorage.getItem('staff_id')){
                    message.error('请先在人事管理中绑定该账号')
                    return
                  }
                  this.setState({
                    addModal: true,
                  });
                }
              }
            >
             派发工单
            </Button>
          }
        {/*  <Tooltip title={'请先查询一次再导出'}>
            <Button
              className={'btn-green'}
              type="primary"
              icon="export"
              style={{ marginLeft: 8 }}
              onClick={this.handleExport}
            >导出
            </Button>
          </Tooltip>*/}
        </FormItem>

      </Form>
    );
  }
  handleExport=()=>{
    const {
      work_orders_list: { searchParams },
    } = this.props;
    console.log('searchParams',searchParams)
    download(`${config.prefix}/wechat_message_files?Authorization=Bearer ${sessionStorage.getItem('token')}&${formateObjToParamStr(({...searchParams, start_time:  moment(searchParams.start_time).format('YYYY-MM-DD 00:00:00'), end_time:  moment(searchParams.end_time).format('YYYY-MM-DD 23:59:59'), order_direction:'desc',company_id:sessionStorage.getItem('company_id')}))}`)

  }
  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'work_orders_list/add',
      payload: {
        ...formValues,
        // publisher_id:sessionStorage.getItem('staff_id')
      },
      callback() {
        message.success('发布工单成功');
        that.setState({
          addModal: false,
        });
        const {
          work_orders_list: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      start_time:moment(new Date().getFullYear()+'-'+(parseInt(new  Date().getMonth())+1)+'-'+'01' , 'YYYY-MM-DD').format('YYYY-MM-DD'),
      end_time: moment(new Date(), 'YYYY-MM-DD').format('YYYY-MM-DD'),
      priority:'',
      status:'',
      page: 1,
      per_page: 30,
    });
  };

  handleEdit = () => {
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: `work_orders_list/edit`,
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
      },
      callback() {
        message.success('修改工单成功');
        that.setState({
          editModal: false,
        });
        const {
          work_orders_list: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleEvaluate= () => {
    const formValues = this.EvaluateForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: `work_orders_list/evaluate`,
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
      },
      callback() {
        message.success('评价工单成功');
        that.setState({
          evaluateModal: false,
        });
        const {
          work_orders_list: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleCancel = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `work_orders_list/cancelIssue`,
      payload: { id },
      callback: () => {
        message.success('取消工单成功');
        const {
          work_orders_list: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `work_orders_list/remove`,
      payload: { id },
      callback: () => {
        message.success('删除工单成功');
        const {
          work_orders_list: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  render() {
    const that = this;
    const {
      work_orders_list: { data, loading, tableY, meta, searchParams, selectedRowKeys },
      global: { gridTableW },
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          const {
            work_orders_list: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '报修时间',
        key: 'report_time',
        width: 150,
        frozen: true,
      },
      {
        name: '户名',
        width: 150,
        key: 'contact_name',
        frozen: true,
        formatter: (event) => {
          return <span style={{color:'blue',textDecoration:'underline',cursor:'pointer'}} onClick={(e) => {
            this.setState({
              editRecord: event.row,
              infoModal: true,
            });
          }}>
            {event.row.contact_name}
          </span>
        },
      },
      {
        name: '优先级',
        width: 100,
        key: 'priority',
        frozen: true,
        formatter: (event) => {
          if(event.row.priority==='一般'){
            return <p className={ 'table-warm table-status' }>一般</p>;
          }
          if(event.row.priority==='紧急'){
            return <p className={ 'table-error table-status' }>紧急</p>;
          }
          return event.row.priority
        },
      },
      {
        name: '状态',
        key: 'status',
        frozen: true,
        width: 120,
        formatter: (event) => {
          switch (event.value) {
            case -1:
              return <p className={ 'table-error table-status' }>已取消</p>;
            case 1:
              return <p className={ 'table-warm table-status' }>未派工</p>;
            case 2:
              return <p  className={ 'table-process table-status' }>已派工、处理中</p>;
            case 3:
              return <p style={{background:'#6ac41a'}} className={ 'table-success table-status' }>已完成、未评价</p>;
            case 4:
              return <p className={ 'table-success table-status' }>已完成、已评价</p>;
            default:
              return ''
          }

        },
      },
      {
        name: '主题',
        width: 150,
        key: 'title',
      },
      {
        name: '派工情况说明',
        width: 150,
        key: 'situation',
      },
      {
        name: '地址',
        width: 150,
        key: 'address',
      },
      {
        name: '联系方式',
        width: 120,
        key: 'mobile',
      },

      {
        name: '类型',
        width: 100,
        key: 'type',
      },

      {
        name: '发布人',
        width: 160,
        key: 'publisher',
        formatter: (event) => {
          return (event.row.publisher.department_name?`${event.row.publisher.department_name} / `:'') + event.row.publisher.name;
        },
      },
      {
        name: '负责人',
        width: 160,
        key: 'supervisor',
        formatter: (event) => {
          return (event.row.supervisor.department_name?`${event.row.supervisor.department_name} / `:'') + event.row.supervisor.name;
        },
      },
      {
        name: '维修人',
        width: 160,
        key: 'inspector',
        formatter: (event) => {
          return (event.row.inspector.department_name?`${event.row.inspector.department_name} / `:'') + event.row.inspector.name;
        },
      },
      {
        name: '处理结果',
        width: 150,
        key: 'process_result',
      },
      {
        name: '水表号',
        width: 100,
        key: 'meter_number',
      },
      {
        name: '水表口径',
        width: 100,
        key: 'caliber',
      },
      {
        name: '备注',
        width: 150,
        key: 'remark',
      },
      {
        name: '操作',
        width: 450,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          <Button
            className={'btn-cyan'}
            type="primary"
            icon="eye"
            size="small"
            onClick={(e) => {
              this.setState({
                editRecord: event.row,
                infoModal: true,
              });
            }
            }
          >工单详情
          </Button>
          {
            (event.row.status!==3&&event.row.status!==4)&&
            <Button
              type="primary"
              size="small"
              icon="edit"
              onClick={(e) => {
                this.setState({
                  editRecord: event.row,
                  editModal: true,
                });
              }
              }
            >工单编辑
            </Button>
          }
          {
            event.row.status ===1 &&
            <Button
              type="danger"
              size="small"
              icon="close"
              onClick={(e) => {
                confirm({
                  title: `确定要取消工单吗?`,
                  content: '请谨慎操作！',
                  okText: '确定',
                  okType: 'danger',
                  cancelText: '取消',
                  centered: true,
                  maskClosable: true,
                  onOk() {
                    that.handleCancel(event.row.id);
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                });
              }
              }
            >取消工单
            </Button>
          }
          {
            (event.row.status===3&&event.row.status!==4)&&event.row.publisher.id===sessionStorage.getItem('user_id')&&
            <Button
              type="primary"
              size="small"
              icon="edit"
              onClick={(e) => {
                this.setState({
                  editRecord: event.row,
                  evaluateModal: true,
                });
              }
              }
            >评价工单
            </Button>
          }
          {
            (event.row.status ===1 ||event.row.status ===-1)&&
            <Button
              type="danger"
              size="small"
              icon="delete"
              onClick={(e) => {
                confirm({
                  title: `确定要删除工单吗?`,
                  content: '请谨慎操作！',
                  okText: '确定',
                  okType: 'danger',
                  cancelText: '取消',
                  centered: true,
                  maskClosable: true,
                  onOk() {
                    that.handleDelete(event.row.id);
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                });
              }
              }
            >删除工单
            </Button>
          }
        </Fragment>,
      },

    ].map(c => ({ ...defaultColumnProperties, ...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>调度中心/派工管理</span>
      </div>
      <div className="table-page">
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            rowsCount={data.length}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (row) => {
                this.props.dispatch({
                  type: 'work_orders_list/changeSelectRow',
                  payload: [row],
                });
              }
            }

          />
          {
            loading && <Loading/>
          }
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }} meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.addModal} modalClass="addModal" title="发布工单"/>}
        className="addModal"
        visible={this.state.addModal}
        centered
        onCancel={() => {
          this.setState({ addModal: false });
        }}
        width={800}
        onOk={this.handleAdd}
      >
        <AddOrEditUser
          wrappedComponentRef={(inst) => this.AddForm = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal"
                                title={`修改 ${this.state.editRecord.number}`}/>}
        destroyOnClose
        visible={this.state.editModal}
        centered
        onOk={this.handleEdit}
        className="editModal"
        width={800}
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ editModal: false, editRecord: {} });
        }}

      >
        <AddOrEditUser
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.EditForm = inst}/>
      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.evaluateModal} modalClass="evaluateModal"
                                title={`评价 ${this.state.editRecord.number}`}/>}
        destroyOnClose
        visible={this.state.evaluateModal}
        centered
        onOk={this.handleEvaluate}
        className="evaluateModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ evaluateModal: false, editRecord: {} });
        }}

      >
        <Evaluate
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.EvaluateForm = inst}/>
      </Modal>
      <Drawer
        title={`${this.state.editRecord.number} 详情`}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            infoModal: false,
            editRecord: {},
          });
        }}

        width={700}
        visible={this.state.infoModal}
      >
        <Detail id={this.state.editRecord.id}></Detail>
      </Drawer>
    </div>;
  }
}

export default BasicList;
